#========================================================================================================
# Strong Partisans, Conditional Democrats? Partisanship and Reactions to Electoral Outcomes in Argentina
## Ezequiel Gonzalez Ocantos, University of Oxford
## Carlos Melendez, Universidade de Lisboa
#========================================================================================================

# ================================
#  Set up
# ================================
if (!requireNamespace("pacman", quietly = TRUE)) install.packages("pacman")
pacman::p_load(rstudioapi, tidyverse, broom, margins, flextable, kableExtra)

set.seed(123)
options(scipen = 999, dplyr.summarise.inform = FALSE)

if (rstudioapi::isAvailable()) {
  this_path <- rstudioapi::getActiveDocumentContext()$path
  if (nzchar(this_path)) setwd(dirname(this_path))
}

if (!file.exists("argentina_may23.RData")) {
  stop("⚠️ No se encuentra el archivo 'argentina_may23.RData' en el directorio: ", getwd())
}
load("argentina_may23.RData")

if (!file.exists("argentina_march23.RData")) {
  stop("⚠️ No se encuentra el archivo 'argentina_mar23.RData' en el directorio: ", getwd())
}
load("argentina_march23.RData")

argentina <- argentina_may23
argentina_mar <- argentina_mar23

# Limpiar objetos temporales
rm(argentina_may23, argentina_mar23, this_path)



# ----------------------
### FIGURES AND TABLES
# ----------------------
  

# ---------------------------
# TABLE 1: Evidence of “enemyopia” in Argentina
# ---------------------------

factor_labels <- list(
  P12_1 = c("Poor", "Rich"), P12_5 = c("Open-minded", "Close-minded"),
  P12_8 = c("From Boca", "From River"), P12_9 = c("Democratic", "Authoritarian"),
  P13_1 = c("Poor", "Rich"), P13_5 = c("Open-minded", "Close-minded"),
  P13_8 = c("From Boca", "From River"), P13_9 = c("Democratic", "Authoritarian"),
  P14_1 = c("Poor", "Rich"), P14_5 = c("Open-minded", "Close-minded"),
  P14_8 = c("From Boca", "From River"), P14_9 = c("Democratic", "Authoritarian")
)

argentina <- argentina %>%
  mutate(across(
    all_of(names(factor_labels)), 
    ~ factor(., levels = c(1, 2), labels = factor_labels[[cur_column()]]), 
    .names = "{.col}r"
  ))

argentina <- argentina %>%
  mutate(
    Kirchnerista_pos_IDr = factor(kirch_pos_id2, levels = c(0, 1),
                                  labels = c("Not a core Kirchnerism supporter", "Core Kirchnerism supporter")),
    JXC_pos_IDr = factor(JxC_pos_id2, levels = c(0, 1),
                         labels = c("Not a core JxC supporter", "Core JxC supporter")),
    liberal_pos_IDr = factor(liberal_pos_id2, levels = c(0, 1),
                             labels = c("Not a core Liberal supporter", "Core Liberal supporter"))
  )
rm (factor_labels)

crear_tabla <- function(variables, posicion) {
  tablas <- lapply(variables, function(var) {
    as.data.frame(round(prop.table(table(argentina[[var]], argentina[[posicion]], useNA = "always"), 2) * 100, 1))
  })
  do.call(rbind, tablas)
}

variables_P12 <- c("P12_1r", "P12_5r", "P12_8r", "P12_9r")
variables_P13 <- c("P13_1r", "P13_5r", "P13_8r", "P13_9r")
variables_P14 <- c("P14_1r", "P14_5r", "P14_8r", "P14_9r")

tabla1 <- rbind(
  crear_tabla(variables_P12, "Kirchnerista_pos_IDr"),
  crear_tabla(variables_P12, "JXC_pos_IDr"),
  crear_tabla(variables_P12, "liberal_pos_IDr")
)
tabla2 <- rbind(
  crear_tabla(variables_P13, "Kirchnerista_pos_IDr"),
  crear_tabla(variables_P13, "JXC_pos_IDr"),
  crear_tabla(variables_P13, "liberal_pos_IDr")
)
tabla3 <- rbind(
  crear_tabla(variables_P14, "Kirchnerista_pos_IDr"),
  crear_tabla(variables_P14, "JXC_pos_IDr"),
  crear_tabla(variables_P14, "liberal_pos_IDr")
)

tabla1$voter <- "Kirchnerist"
tabla2$voter <- "JxC"
tabla3$voter <- "Liberal"

tabla <- rbind(tabla1, tabla2, tabla3)
tabla <- subset(tabla, subset = !is.na(Var1) & !is.na(Var2))
names(tabla) <- c("Pairs", "Identity", "Percent", "Voter")

library(tidyverse)

tabla <- tabla %>%
  distinct() %>%                      
  mutate(Pairs = as.character(Pairs), 
         Percent = as.numeric(Percent))

tabla_final <- tabla %>%
  pivot_wider(
    names_from = Pairs,                
    values_from = Percent,             
    values_fill = 0                   
  )
kable(tabla_final) %>% kable_classic_2()

# ---------------------------
# FIGURE 1 1: Plausibility of scenarios according to respondents - % choosing “somewhat/highly probable” by treatment arm and partisan subgroup
# ---------------------------

argentina$P20r2 <- factor (argentina$P20, levels = c(1:5), labels = c("Muy imposible o algo imposible", "Muy imposible o algo imposible", "Ni posible ni imposible", "Muy posible o algo posible", "Muy posible o algo posible"))

tabla <- argentina %>% filter (!is.na(argentina$P20r2)) %>% 
  group_by(treat, P20r2) %>% 
  summarise (Frec=n()) %>% 
  mutate (Porc=round(Frec/(sum(Frec))*100,1)) %>% 
  filter (P20r2=="Muy posible o algo posible")

tabla <- tabla[,c(1,4)]
tabla$Identity <- "All respondents"

tabla1 <- argentina %>% filter (!is.na(argentina$P20r2)) %>% 
  group_by(treat, kirch_pos_id2, P20r2) %>% 
  summarise (Frec=n()) %>% 
  mutate (Porc=round(Frec/(sum(Frec))*100,1)) %>% 
  filter (P20r2=="Muy posible o algo posible") %>% 
  filter (kirch_pos_id2==1)


tabla1 <- tabla1[,c(1,5)]
tabla1$Identity <- "Strong Kirchnerism"

tabla <- rbind(tabla, tabla1)

tabla1 <- argentina %>% filter (!is.na(argentina$P20r2)) %>% 
  group_by(treat, JxC_pos_id2, P20r2) %>% 
  summarise (Frec=n()) %>% 
  mutate (Porc=round(Frec/(sum(Frec))*100,1)) %>% 
  filter (P20r2=="Muy posible o algo posible") %>% 
  filter (JxC_pos_id2==1)


tabla1 <- tabla1[,c(1,5)]
tabla1$Identity <- "Strong JxC"

tabla <- rbind(tabla, tabla1)

tabla1 <- argentina %>% filter (!is.na(argentina$P20r2)) %>% 
  group_by(treat, liberal_pos_id2, P20r2) %>% 
  summarise (Frec=n()) %>% 
  mutate (Porc=round(Frec/(sum(Frec))*100,1)) %>% 
  filter (P20r2=="Muy posible o algo posible") %>% 
  filter (liberal_pos_id2==1)


tabla1 <- tabla1[,c(1,5)]
tabla1$Identity <- "Strong Liberal"

tabla <- rbind(tabla, tabla1)

greys <- RColorBrewer::brewer.pal(n = 6, name = "Greys")
greys <- greys[2:6]

tabla %>% ggplot(aes(x=treat, y=Porc, fill=Identity))+
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = Porc), 
            position = position_dodge(width = 0.9), 
            vjust = -0.5, 
            size = 2) +  # Tamaño del texto
  scale_y_continuous(breaks = seq(0, 100, by = 10), limits = c(0, 100)) + # Ajuste del eje Y
  labs(x = "\nTreat",
       y = "Percent\n\n",
       fill="Identity:") +
  theme_minimal()+
  scale_fill_manual(values = greys)+
  theme(
    axis.title = element_text(size=8, color="black"),
    axis.text = element_text(size=6, color="black"),
    legend.text = element_text(size=6, color="black"),
    legend.position="bottom",
    legend.title = element_text(size=8, color="black")
  )+
  guides(fill = guide_legend(keywidth = 0.5, keyheight = 0.5))

# ---------------------------
# FIGURE 2: Marginal effects of the interaction terms on emotions
# ---------------------------

argentina <- argentina %>%
  mutate(
    strong_kirch= ifelse(strong_kirch == "Strong (1)", 1, 0),
    strong_jxc = ifelse(strong_jxc == "Strong (1)", 1, 0),
    strong_lib = ifelse(strong_lib == "Strong (1)", 1, 0)
  )


# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Kirchnerism"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " ")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatKirchnerism`, 
        `Var_dydx_treatKirchnerism`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatKirchnerism`,
        variance = `Var_dydx_treatKirchnerism`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
greys <- rev(RColorBrewer::brewer.pal(n = 6, name = "Greys")[3:7])
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: Kirchnerism",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -Juntos por el Cambio

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Juntos por el Cambio"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " ")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatJuntos por el Cambio`, 
        `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatJuntos por el Cambio`,
        variance = `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: JXC",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )


## Now with all -La Libertad Avanza

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "La Libertad Avanza"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " ")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatLa Libertad Avanza`, 
        `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatLa Libertad Avanza`,
        variance = `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: LLA",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



# ---------------------------
# FIGURE 3:  Marginal effects of the interaction terms on democratic attitudes
# ---------------------------

## Kirchnerism 

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Kirchnerism"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " ")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatKirchnerism`, 
        `Var_dydx_treatKirchnerism`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatKirchnerism`,
        variance = `Var_dydx_treatKirchnerism`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: Kirchnerism",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )

## Now with all -Juntos por el Cambio

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Juntos por el Cambio"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " ")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatJuntos por el Cambio`, 
        `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatJuntos por el Cambio`,
        variance = `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: JxC",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -La Libertad Avanza

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "La Libertad Avanza"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " ")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatLa Libertad Avanza`, 
        `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatLa Libertad Avanza`,
        variance = `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: LLA",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



#-------------------
### REFERENCES IN TEXT
#--------------------

# P.18

argentina <- argentina %>% mutate(P20r = factor(P20,
                                                levels = c(1:5),
                                                labels = c(
                                                  "Highly impossible",
                                                  "Somewhat impossible",
                                                  "Neither possible nor impossible",
                                                  "Somewhat possible",
                                                  "Highly possible"
                                                )
))
argentina %>%
  filter(treat != "Control") %>% 
  { round(prop.table(table(.$P20r, .$treat), 2) * 100, 1) } %>% 
  kable() %>% 
  kable_classic()


#-------------------
### FOOTNOTES
#-------------------

# FT11:

# Recode P10 with value labels
argentina <- argentina %>%
  mutate(P10r = factor(P10,
                       levels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 96, 97, 98),
                       labels = c(
                         "Sergio Massa",
                         "Daniel Scioli",
                         "Wado de Pedro",
                         "Patricia Bullrich",
                         "Horacio Rodríguez Larreta",
                         "Facundo Manes",
                         "Gerardo Morales",
                         "José Luis Espert",
                         "Javier Milei",
                         "Myriam Bergman",
                         "Gabriel Solano",
                         "Manuela Castañeira",
                         "Otro",
                         "Ninguno",
                         "No lo sé"
                       )
  ))

argentina %>%
  group_by(P10r) %>% 
  summarise(Freq=n()) %>% 
  mutate(Perc=round(Freq/sum(Freq)*100,1)) %>% 
  kable(col.names = c("Candidate", "Freq", "Perc")) %>% 
  kable_classic()


#-------------------
### APPENDIX
#-------------------

#-------------------
### Table A1. Sample characteristics
#-------------------

summ_stats <- function(x) {
  x <- x[!is.na(x)]
  tibble(
    N    = length(x),
    Mean = if (length(x)) mean(x) else NA_real_,
    SD   = if (length(x) > 1) sd(x) else NA_real_,
    Min  = if (length(x)) min(x) else NA_real_,
    Max  = if (length(x)) max(x) else NA_real_
  )
}

dat <- argentina %>%
  mutate(
    # Age (keep 18–99)
    age_use = ifelse(!is.na(resp_age) & resp_age >= 18 & resp_age <= 99, resp_age, NA),
    
    # Female (1 = Male, 2 = Female)
    female = ifelse(resp_gender == 'Female', 1,
                    ifelse(resp_gender == 'Male', 0, NA)),
    
    # From Buenos Aires (1–2 = Buenos Aires; 3–24 = Other; 99 = NA)
    from_ba = case_when(
      P03 %in% 1:2  ~ 1,
      P03 %in% 3:24 ~ 0,
      TRUE ~ NA_real_
    ),
    
    # SES categories
    ses_poor = ifelse(resp_ses %in% c(1, 2), 1, 
                      ifelse(resp_ses %in% c(3, 4, 5), 0, NA)),
    ses_abc1 = ifelse(resp_ses == 5, 1, 0),
    ses_c2   = ifelse(resp_ses == 4, 1, 0),
    ses_c3   = ifelse(resp_ses == 3, 1, 0),
    
    # Education (as numeric)
    educ_use = suppressWarnings(as.numeric(P02A))
  )

rows <- list(
  "Age"                                       = summ_stats(dat$age_use),
  "Female"                                    = summ_stats(dat$female),
  "From the City or Province of Buenos Aires" = summ_stats(dat$from_ba),
  "Poor (D1, D2, E1)"                         = summ_stats(dat$ses_poor),
  "ABC1"                                      = summ_stats(dat$ses_abc1),
  "C2"                                        = summ_stats(dat$ses_c2),
  "C3"                                        = summ_stats(dat$ses_c3),
  "Education"                                 = summ_stats(dat$educ_use)
)

tabla_a1 <- bind_rows(rows, .id = "Characteristic")

tabla_a1 <- tabla_a1 %>%
  mutate(
    N    = as.integer(N),
    Mean = round(Mean, 3),
    SD   = round(SD, 2),
    Min  = round(Min, 0),
    Max  = round(Max, 0)
  )

tabla_a1 %>% kable() %>% kable_classic()
#-------------------
### Figure A1. Distribution of affect for the three main political groups – March and May 2023
#-------------------


# --- Data ---

make_prop <- function(x, survey, party) {
  tibble(Valor = x) |>
    filter(!is.na(Valor)) |>
    count(Valor, name = "n") |>
    mutate(
      Porcentaje = round(100 * n / sum(n), 1),
      Encuesta   = survey,
      Partido    = party
    ) |>
    select(Valor, Porcentaje, Encuesta, Partido)
}

tabla <- bind_rows(
  make_prop(argentina_mar$kirchnerismo2, "March", "Kirchnerism"),
  make_prop(argentina$like_kirch,  "May",   "Kirchnerism"),
  make_prop(argentina_mar$jxc,           "March", "JxC"),
  make_prop(argentina$like_jxc,    "May",   "JxC"),
  make_prop(argentina_mar$liberal,       "March", "Liberals"),
  make_prop(argentina$like_lib,    "May",   "Liberals")
) |>
  mutate(
    Encuesta = factor(Encuesta, levels = c("March", "May")),
    Partido  = factor(Partido,  levels = c("Kirchnerism", "JxC", "Liberals")),
    # Ordenar "Valor" de forma natural (numérico si aplica)
    Valor = if (suppressWarnings(all(!is.na(as.numeric(as.character(Valor)))))) {
      factor(Valor, levels = sort(unique(as.numeric(as.character(Valor)))))
    } else {
      factor(Valor)
    }
  )

# --- Plot ---
greys <- RColorBrewer::brewer.pal(n = 6, name = "Greys")[2:6]
greys <- greys[c(2,4)]

ggplot(tabla, aes(x = Valor, y = Porcentaje, fill = Encuesta)) +
  geom_col(width = 0.9, position = position_dodge()) +
  geom_text(aes(label = paste0(Porcentaje, "%")),
            vjust = -0.9, position = position_dodge(0.9), size = 2) +
  scale_fill_manual(values = greys) +  # tonos definidos manualmente
  scale_y_continuous(expand = c(0, 0), breaks = seq(0, 100, 20), limits = c(0, 100)) +
  labs(x = NULL, y = "Share (%)", fill = NULL) +
  theme_classic() +
  theme(
    axis.text.x = element_text(size = 8, colour = "black"),
    axis.text.y = element_text(size = 8, colour = "black"),
    strip.text = element_text(face = "bold", size = 9),
    panel.spacing = unit(1, "lines")
  ) +
  facet_grid(Partido ~ .)



#-----------------
##### Table B1. In/Outgroup stereotypes by partisan group
#-----------------

factor_labels <- list(
  P12_1 = c("Poor", "Rich"),P12_2=c("Hard-working", "Lazy"),
  P12_3 = c("Inteligent", "Ignorant"), P12_4 = c ("Honest", "Dishonest"),
  P12_5 = c("Open-minded", "Close-minded"), P12_6 = c ("Old", "Young"),
  P12_7 = c("Selfish", "Generous"), P12_8 = c("From Boca", "From River"), 
  P12_9 = c("Democratic", "Authoritarian"),
  P13_1 = c("Poor", "Rich"),P13_2=c("Hard-working", "Lazy"),
  P13_3 = c("Inteligent", "Ignorant"), P13_4 = c ("Honest", "Dishonest"),
  P13_5 = c("Open-minded", "Close-minded"), P13_6 = c ("Old", "Young"),
  P13_7 = c("Selfish", "Generous"), P13_8 = c("From Boca", "From River"), 
  P13_9 = c("Democratic", "Authoritarian"),
  P14_1 = c("Poor", "Rich"),P14_2=c("Hard-working", "Lazy"),
  P14_3 = c("Inteligent", "Ignorant"), P14_4 = c ("Honest", "Dishonest"),
  P14_5 = c("Open-minded", "Close-minded"), P14_6 = c ("Old", "Young"),
  P14_7 = c("Selfish", "Generous"), P14_8 = c("From Boca", "From River"), 
  P14_9 = c("Democratic", "Authoritarian")
)

argentina <- argentina %>%
  mutate(
    Kirchnerista_pos_IDr = factor(kirch_pos_id2, levels = c(0, 1),
                                  labels = c("Not a core Kirchnerism supporter", "Core Kirchnerism supporter")),
    JXC_pos_IDr = factor(JxC_pos_id2, levels = c(0, 1),
                         labels = c("Not a core JxC supporter", "Core JxC supporter")),
    liberal_pos_IDr = factor(liberal_pos_id2, levels = c(0, 1),
                             labels = c("Not a core Liberal supporter", "Core Liberal supporter"))
  )

argentina <- argentina %>%
  mutate(across(
    all_of(names(factor_labels)), 
    ~ factor(., levels = c(1, 2), labels = factor_labels[[cur_column()]]), 
    .names = "{.col}r"
  ))

crear_tabla <- function(variables, posicion) {
  tablas <- lapply(variables, function(var) {
    as.data.frame(round(prop.table(table(argentina[[var]], argentina[[posicion]], useNA = "always"), 2) * 100, 1))
  })
  do.call(rbind, tablas)
}

variables_P12 <- c("P12_1r","P12_2r" ,"P12_3r","P12_4r", "P12_5r", "P12_6r","P12_7r", "P12_8r", "P12_9r")
variables_P13 <- c("P13_1r","P13_2r" ,"P13_3r","P13_4r", "P13_5r", "P13_6r","P13_7r", "P13_8r", "P13_9r")
variables_P14 <- c("P14_1r","P14_2r" ,"P14_3r","P14_4r", "P14_5r", "P14_6r","P14_7r", "P14_8r", "P14_9r")

tabla1 <- rbind(
  crear_tabla(variables_P12, "Kirchnerista_pos_IDr"),
  crear_tabla(variables_P12, "JXC_pos_IDr"),
  crear_tabla(variables_P12, "liberal_pos_IDr")
)
tabla2 <- rbind(
  crear_tabla(variables_P13, "Kirchnerista_pos_IDr"),
  crear_tabla(variables_P13, "JXC_pos_IDr"),
  crear_tabla(variables_P13, "liberal_pos_IDr")
)
tabla3 <- rbind(
  crear_tabla(variables_P14, "Kirchnerista_pos_IDr"),
  crear_tabla(variables_P14, "JXC_pos_IDr"),
  crear_tabla(variables_P14, "liberal_pos_IDr")
)

tabla1$voter <- "Kirchnerist"
tabla2$voter <- "JxC"
tabla3$voter <- "Liberal"

tabla <- rbind(tabla1, tabla2, tabla3)
tabla <- subset(tabla, subset = !is.na(Var1) & !is.na(Var2))
names(tabla) <- c("Pairs", "Identity", "Percent", "Voter")


tabla <- tabla %>%
  distinct() %>%                      
  mutate(Pairs = as.character(Pairs), 
         Percent = as.numeric(Percent))

tabla_final <- tabla %>%
  pivot_wider(
    names_from = Pairs,                
    values_from = Percent,             
    values_fill = 0                   
  )

kable(tabla_final) %>% kable_classic_2()

#-----------------
##### Table C1. Partisan Affect by Party Family
#-----------------

argentina <- argentina %>%
  mutate(
    party_group = case_when(
      P8 %in% c(1, 3, 7, 8)            ~ "Juntos por el Cambio - JXC, PRO, UCR, CC",
      P8 %in% c(2, 4, 5, 6)            ~ "Kirchnerism - Kirchnerismo, Peronismo, Frente Renovador",
      P8 %in% c(9,10,11,12)            ~ "Left - Frente de izquierda, Partido Obrero, PTS, NMS",
      P8 %in% c(13)                    ~ "Libertarians - La Libertad Avanza",
      TRUE                             ~ NA_character_
    ),
    party_group = factor(
      party_group,
      levels = c(
        "Juntos por el Cambio - JXC, PRO, UCR, CC",
        "Kirchnerism - Kirchnerismo, Peronismo, Frente Renovador",
        "Left - Frente de izquierda, Partido Obrero, PTS, NMS",
        "Libertarians - La Libertad Avanza"
      )
    )
  )

items <- paste0("P9_", 1:8)

argentina <- argentina %>%
  mutate(across(all_of(items), ~ suppressWarnings(as.numeric(.))))

item_labels <- c(
  "When I talk about this party and its allies, I normally use “us” instead of “them”",
  "I am interested in what other people think about this party and its allies",
  "When someone criticizes this party and its allies, I feel personally offended",
  "I have a lot in common with those who vote for this party and its allies",
  "I don’t like it when this party or its allies do poorly in surveys",
  "When I meet someone that supports this party and its allies, I feel connected to this person",
  "When someone praises this party and its allies, I feel good",
  "I don’t like it when there are fights between members of my party and its allies"
)

items; item_labels

stopifnot(all(items %in% names(argentina)))

argentina <- argentina %>%
  mutate(
    affect_index = rowMeans(dplyr::select(., P9_1:P9_8), na.rm = F)
  )


# --- 2) Means by party group for each item ---
item_means <- argentina %>%
  select(party_group, all_of(items)) %>%
  pivot_longer(cols = all_of(items),
               names_to = "item",
               values_to = "value") %>%
  group_by(party_group, item) %>%
  summarise(mean = mean(value, na.rm = TRUE), .groups = "drop") %>%
  mutate(
    order = match(item, items),
    label = item_labels[order]
  ) %>%
  arrange(order)

index_means <- argentina %>%
  group_by(party_group) %>%
  summarise(mean = mean(affect_index, na.rm = TRUE), .groups = "drop") %>%
  mutate(label = "Partisan Affect Index", order = 0)

tabla_affect <- bind_rows(
  index_means %>% select(party_group, mean, label, order),
  item_means   %>% select(party_group, mean, label, order)
) %>%
  mutate(mean = round(mean, 2)) %>%
  arrange(order, label) %>%
  select(Label = label, party_group, mean) %>%
  pivot_wider(
    names_from  = party_group,
    values_from = mean
  )
tabla_affect %>% kable() %>%  kable_classic()



#----------------
#### Table D1. Regression results with emotions as dependent variables (NO CONTROLS)
#----------------

mod1 <- lm(exp_anxiety~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod2 <- lm(exp_anger~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod3 <- lm(exp_fear~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod4 <- lm(exp_hope~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod5 <- lm(exp_happiness~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))

mod6 <- lm(exp_anxiety~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod7 <- lm(exp_anger~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod8 <- lm(exp_fear~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod9 <- lm(exp_hope~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod10 <- lm(exp_happiness~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))

mod11 <- lm(exp_anxiety~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod12 <- lm(exp_anger~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod13 <- lm(exp_fear~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod14 <- lm(exp_hope~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod15 <- lm(exp_happiness~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))

mod1a <- lm(exp_anxiety~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod2a <- lm(exp_anger~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod3a <- lm(exp_fear~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod4a <- lm(exp_hope~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod5a <- lm(exp_happiness~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))

mod6a <- lm(exp_anxiety~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod7a <- lm(exp_anger~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod8a <- lm(exp_fear~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod9a <- lm(exp_hope~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod10a <- lm(exp_happiness~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))

mod11a <- lm(exp_anxiety~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod12a <- lm(exp_anger~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod13a <- lm(exp_fear~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod14a <- lm(exp_hope~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod15a <- lm(exp_happiness~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))

mod1b <- lm(exp_anxiety~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod2b <- lm(exp_anger~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod3b <- lm(exp_fear~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod4b <- lm(exp_hope~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod5b <- lm(exp_happiness~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))

mod6b <- lm(exp_anxiety~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod7b <- lm(exp_anger~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod8b <- lm(exp_fear~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod9b <- lm(exp_hope~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod10b <- lm(exp_happiness~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))

mod11b <- lm(exp_anxiety~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod12b <- lm(exp_anger~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod13b <- lm(exp_fear~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod14b <- lm(exp_hope~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod15b <- lm(exp_happiness~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))




# --- Helper: tidy + star and select (term, estimate) ---
tidy_with_stars <- function(model) {
  broom::tidy(model) %>%
    mutate(estimate = ifelse(p.value < 0.05,
                             sprintf("%.2f*", estimate),
                             sprintf("%.3f", round(estimate, 3)))) %>%
    select(term, estimate)
}

# --- Helper: build a wide table from a *named* list of models ---
make_table <- function(model_names, caption) {
  # fetch models by name from the calling environment
  models <- mget(model_names, inherits = TRUE)
  
  # list of tidy dfs, one per model, preserving order
  dfs <- map(models, tidy_with_stars)
  
  # reduce via full_join by 'term'
  tabla <- reduce(dfs, ~ full_join(.x, .y, by = "term"))
  
  # set column names: Predictor + model names (in the same order)
  colnames(tabla) <- c("Predictor", model_names)
  
  # style with flextable
  flextable(tabla) %>%
    set_caption(caption = caption) %>%
    theme_vanilla() %>%
    autofit() %>%
    bold(part = "header") %>%
    bg(part = "header", bg = "#D3D3D3") %>%
    bg(i = seq(1, nrow(tabla), 2), bg = "#F7F7F7") %>%
    align(align = "center", part = "all") %>%
    font(part = "all", fontname = "Arial") %>%
    hline_top(part = "body", border = fp_border_default()) %>%
    hline_bottom(part = "body", border = fp_border_default()) %>%
    add_footer_lines(values = "Note: Coefficients with * are significant at p < 0.05.") %>%
    set_table_properties(width = 0.9)
}


# Anxiety
mods_anxiety <- c("mod1","mod6","mod11",
                  "mod1a","mod6a","mod11a",
                  "mod1b","mod6b","mod11b")

# Anger
mods_anger   <- c("mod2","mod7","mod12",
                  "mod2a","mod7a","mod12a",
                  "mod2b","mod7b","mod12b")

# Fear
mods_fear    <- c("mod3","mod8","mod13",
                  "mod3a","mod8a","mod13a",
                  "mod3b","mod8b","mod13b")

# Hope
mods_hope    <- c("mod4","mod9","mod14",
                  "mod4a","mod9a","mod14a",
                  "mod4b","mod9b","mod14b")

# Happiness
mods_happy   <- c("mod5","mod10","mod15",
                  "mod5a","mod10a","mod15a",
                  "mod5b","mod10b","mod15b")

tab_anxiety  <- make_table(mods_anxiety, "Anxiety (*)")
tab_anger    <- make_table(mods_anger,   "Anger (*)")
tab_fear     <- make_table(mods_fear,    "Fear (*)")
tab_hope     <- make_table(mods_hope,    "Hope (*)")
tab_happy    <- make_table(mods_happy,   "Happiness (*)")

# Print (or save) the tables
tab_anxiety
tab_anger
tab_fear
tab_hope
tab_happy


#-------------
### Table D2. Regression results with democratic attitudes as dependent variables
#-------------
mod1 <- lm(demo_pref~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod2 <- lm(election_trust~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod3 <- lm(demo_sat~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))

mod1a <- lm(demo_pref~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod2a <- lm(election_trust~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod3a <- lm(demo_sat~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))

mod1b <- lm(demo_pref~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod2b <- lm(election_trust~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod3b <- lm(demo_sat~treat+kirch_pos_id2+treat*kirch_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))

mod6 <- lm(demo_pref~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod7 <- lm(election_trust~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod8 <- lm(demo_sat~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))

mod6a <- lm(demo_pref~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod7a <- lm(election_trust~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod8a <- lm(demo_sat~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))

mod6b <- lm(demo_pref~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod7b <- lm(election_trust~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod8b <- lm(demo_sat~treat+JxC_pos_id2+treat*JxC_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))

mod11 <- lm(demo_pref~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod12 <- lm(election_trust~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))
mod13 <- lm(demo_sat~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Kirchnerism"))

mod11a <- lm(demo_pref~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod12a <- lm(election_trust~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))
mod13a <- lm(demo_sat~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="Juntos por el Cambio"))

mod11b <- lm(demo_pref~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod12b <- lm(election_trust~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))
mod13b <- lm(demo_sat~treat+liberal_pos_id2+treat*liberal_pos_id2, data = argentina,    subset = (treat=="Control"| treat=="La Libertad Avanza"))

# --- Define model name sets by outcome ---
mods_demo_pref <- c(
  "mod1","mod6","mod11",
  "mod1a","mod6a","mod11a",
  "mod1b","mod6b","mod11b"
)

mods_election_trust <- c(
  "mod2","mod7","mod12",
  "mod2a","mod7a","mod12a",
  "mod2b","mod7b","mod12b"
)

mods_demo_sat <- c(
  "mod3","mod8","mod13",
  "mod3a","mod8a","mod13a",
  "mod3b","mod8b","mod13b"
)

# --- Build the three tables ---
tab_demo_pref       <- make_table(mods_demo_pref,       "Democratic preferable (*)")
tab_election_trust  <- make_table(mods_election_trust,  "Trust in elections (*)")
tab_demo_sat        <- make_table(mods_demo_sat,        "Democratic satisfaction (*)")

# --- Show in Viewer ---
tab_demo_pref
tab_election_trust
tab_demo_sat

#-------------------
#### Figure E1. Marginal effects of the interaction term on emotions controlling for education.
#-------------------

## Kirchnerism 

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")

results_list <- list()

for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Kirchnerism"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatKirchnerism`, 
        `Var_dydx_treatKirchnerism`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatKirchnerism`,
        variance = `Var_dydx_treatKirchnerism`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
greys <- rev(RColorBrewer::brewer.pal(n = 6, name = "Greys")[3:7])
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: Kirchnerism",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -Juntos por el Cambio

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Juntos por el Cambio"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatJuntos por el Cambio`, 
        `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatJuntos por el Cambio`,
        variance = `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: JXC",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -La Libertad Avanza

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "La Libertad Avanza"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, "+ resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatLa Libertad Avanza`, 
        `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatLa Libertad Avanza`,
        variance = `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: LLA",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



#-------------------
#### Figure E2. Marginal effects of the interaction term on emotions controlling for for income education, age and gender
#-------------------

## Kirchnerism 

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")

results_list <- list()

for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Kirchnerism"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_ses + resp_age_z + resp_gender + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatKirchnerism`, 
        `Var_dydx_treatKirchnerism`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatKirchnerism`,
        variance = `Var_dydx_treatKirchnerism`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: Kirchnerism",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )


## Now with all -Juntos por el Cambio

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Juntos por el Cambio"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_ses + resp_age_z + resp_gender + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatJuntos por el Cambio`, 
        `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatJuntos por el Cambio`,
        variance = `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: JXC",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -La Libertad Avanza

# Define variables
outcomes <- c('exp_anxiety', 'exp_anger', 'exp_fear', 'exp_hope', 'exp_happiness')
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "La Libertad Avanza"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_ses + resp_age_z + resp_gender + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatLa Libertad Avanza`, 
        `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatLa Libertad Avanza`,
        variance = `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "exp_anxiety" = " Anxiety",
                                "exp_anger" = " Anger",
                                "exp_fear" = " Fear",
                                "exp_hope" = " Hope",
                                "exp_happiness" = " Happiness"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: LLA",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



#------------------
#### Figure E3. Marginal effects of the interaction term on democratic attitudes controlling for education
#------------------

## Kirchnerism 

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Kirchnerism"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, "+ resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatKirchnerism`, 
        `Var_dydx_treatKirchnerism`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatKirchnerism`,
        variance = `Var_dydx_treatKirchnerism`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: Kirchnerism",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -Juntos por el Cambio

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Juntos por el Cambio"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, "+ resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatJuntos por el Cambio`, 
        `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatJuntos por el Cambio`,
        variance = `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: JXC",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -La Libertad Avanza

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "La Libertad Avanza"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatLa Libertad Avanza`, 
        `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatLa Libertad Avanza`,
        variance = `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: LLA",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )


#------------------
#### Figure E4. Marginal effects of the interaction term on democratic attitudes controlling for income, education, age and gender
#------------------


## Kirchnerism 

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Kirchnerism"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_ses + resp_age_z + resp_gender + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatKirchnerism`, 
        `Var_dydx_treatKirchnerism`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatKirchnerism`,
        variance = `Var_dydx_treatKirchnerism`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: Kirchnerism",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -Juntos por el Cambio

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "Juntos por el Cambio"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_ses + resp_age_z + resp_gender + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatJuntos por el Cambio`, 
        `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatJuntos por el Cambio`,
        variance = `Var_dydx_treatJuntos por el Cambio`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: JXC",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )



## Now with all -La Libertad Avanza

# Define variables
outcomes <- c("demo_sat", "demo_pref", "election_trust")
strong_vars <- c("strong_kirch", "strong_jxc", "strong_lib")


results_list <- list()


for (outcome in outcomes) {
  for (strong_var in strong_vars) {
    # Subset data for "Kirchnerism" treatment
    argentina_ft <- argentina %>%
      filter(treat %in% c("Control", "La Libertad Avanza"))
    
    model <- lm(as.formula(paste0(outcome, " ~ treat * ", strong_var, " + resp_ses + resp_age_z + resp_gender + resp_edu")),
                data = argentina_ft)
    
    marg_effects <- margins(model, variables = "treat", at = setNames(list(c(0, 1)), strong_var))
    
    # Convert effects to a data frame
    marg_effects_clean <- as.data.frame(marg_effects) %>%
      dplyr::select(
        !!sym(strong_var), 
        `dydx_treatLa Libertad Avanza`, 
        `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      rename(
        group = !!sym(strong_var),
        marginal_effect = `dydx_treatLa Libertad Avanza`,
        variance = `Var_dydx_treatLa Libertad Avanza`
      ) %>%
      mutate(
        group = ifelse(group == 1, paste("Strong", toupper(gsub("strong_", "", strong_var))), "Rest of Sample"),
        partisan_group = toupper(gsub("strong_", "", strong_var)),
        outcome = outcome,
        se = sqrt(variance),
        lower = marginal_effect - 1.96 * se,
        upper = marginal_effect + 1.96 * se
      )
    
    results_list[[paste0(outcome, "_", strong_var)]] <- marg_effects_clean
  }
}

# Combine  results into a  dataframe
results <- bind_rows(results_list)

# Map outcomes to  labels
results <- results %>%
  mutate(outcome_label = recode(outcome,
                                "demo_sat" = "Satisfaction with Democracy",
                                "demo_pref" = "Democracy Preferable",
                                "election_trust" = "Election Trustworthy"))

# Plot all outcomes 
ggplot(results, aes(x = marginal_effect, y = group,
                    shape = partisan_group, color = partisan_group)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  facet_grid(partisan_group ~ outcome_label, scales = "free_y", space = "free_y") +
  labs(
    x = "Marginal Effect",
    y = "",
    title = "Marginal Effect: LLA",
    shape = "Partisan Group",
    color = "Partisan Group"
  ) +
  scale_color_manual(values = greys) +
  scale_shape_manual(values = c(16, 17, 15)) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 10, face = "bold"),
    axis.title = element_text(size = 10),
    axis.text = element_text(size = 10),
    plot.title = element_text(size = 12, face = "bold", hjust = 0.5)
  )












